<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;
require_once LIBRARIES_ENTITIES_ITEMS;
//require LIBRARIES_ENTITIES_PROVINCES;
require_once LIBRARIES_ENTITIES_CUSTOMERS;
require_once LIBRARIES_ENTITIES_ORDERS;
require_once LIBRARIES_ENTITIES_ORDERDETAIL;

class ComPaymentController {

    public function invoke() {

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }


        // CHECK ACTION
        // destroy cart action
        if ($action == 'destroy') {
            unset($_SESSION['cart']);
            Utility::redirect('.');
        } else if ($action == 'payment') {
            $customerName = $_POST['txtCustomerName'];
            $gender = $_POST['rdoGender'];
            $phoneNumber = $_POST['txtPhoneNumber'];
            $address = $_POST['txtAddress'];
            $email = $_POST['txtEmail'];
            $provine = $_POST['slProvine'];
            $description = $_POST['txtDescription'];

            $result = $this->payment($customerName, $gender, $phoneNumber, $address, $email, $provine, $_SESSION['cart'], $description);
            if ($result == OK) {
                $derectory = dirname(__FILE__);
                $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'payment_successful.html');
                $xtemplate->parse('main');
                $xtemplate->out('main');

                // destroy cart when successful
                unset($_SESSION['cart']);                
            }
        } else {

//            echo 'here';
            if (isset($_SESSION['cart']) && count($_SESSION['cart'] > 0)) {
                $derectory = dirname(__FILE__);
                $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'payment.html');

                // get list of provine
                $provines = $this->getProviceList();

                if (count($provines) > 0) {
                    for ($i = 0; $i < count($provines); $i++) {
                        $xtemplate->assign('P_ID', $provines[$i]->getID());
                        $xtemplate->assign('P_Name', $provines[$i]->getName());
                        $xtemplate->parse('main.provine_list');
                    }
                }
                
                $total = 0;
                foreach ($_SESSION['cart'] as $item) {
                    if ($item['propertyID'] != '') {
                        // item property object
                        $itemProperty = $this->getItemPropertyByID($item['propertyID']);
                        $xtemplate->assign('ITEM_PROPERTY_VALUE', $itemProperty->getValue());
                    } else {
                        $xtemplate->assign('ITEM_PROPERTY_VALUE', '');
                    }

                    // item object 
                    $itemObj = $this->getItemByID($item['itemID']);

                    $xtemplate->assign('ITEM_ID', $item['itemID']);
                    $xtemplate->assign('ITEM_NAME', $itemObj->getName());
                    $xtemplate->assign('ITEM_IMAGE', $itemObj->getImage());
                    $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($item['itemPrice']));
                    $xtemplate->assign('ITEM_QUANTITY', $item['quantity']);
                    $xtemplate->assign('TOTAL_EACH_ITEM', Utility::formatToCurrencyString($item['totalEachItem']));

                    // calculate total
                    $total = $total + $item['totalEachItem'];

                    $xtemplate->parse('main.item_list');
                }

                // show action buttons
                $xtemplate->parse('main.action_button');
                $xtemplate->assign('TOTAL', Utility::formatToCurrencyString($total));
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                Utility::redirect('.');
            }
        }
    }

    // get an item_property by item property ID
    private function getItemPropertyByID($itemPropertyID) {
        $db = new Database();
        try {
            $itemProperty = new ItemProperties();
            $itemProperty->setID($itemPropertyID);
            $result = $itemProperty->getItemPropertyByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // get item detail by item ID
    private function getItemByID($itemID) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setID($itemID);
            $result = $item->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    private function getProviceList() {
        $db = new Database();
        try {
            $province = new Provinces();
            $result = $province->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // add a customer 
    private function addCustomer() {
        $db = new Database();
        try {
            $provine = new Customers();
            $result = $provine->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function payment($customerName, $gender, $phoneNumber, $address, $email, $provineID, $cart, $description) {
        $db = new Database();
        try {

            // add customer
            $customer = new Customers();
            $customer->setName($customerName);
            $customer->setGender($gender);
            $customer->setPhone($phoneNumber);
            $customer->setAddress($address);
            $customer->setEmail($email);
            $customer->setProvinceID($provineID);
            $customerID = $customer->add($db);



            // add order
            $order = new Orders();
//            $order->setCreatedDate(date('Y-m-d H:I:s'));
            $order->setCreatedDate(Utility::getCurrentDate());
            $order->setCustomerID($customerID);
            $order->setDescription($description);

            $orderID = $order->add($db);

            // add order
            foreach ($_SESSION['cart'] as $item) {
                $orderDetail = new OrderDetail();
                $orderDetail->setItemID($item['itemID']);
                $orderDetail->setQuantity($item['quantity']);
                if ($item['propertyID'] != '') {
                    $orderDetail->setItemPropertyID($item['propertyID']);
                }
                $orderDetail->setOrderID($orderID);
                $orderDetail->setPrice($item['itemPrice']);
                $orderDetail->add($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
